package com.yyk.yykywd.ui.home.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.View;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.androidkun.xtablayout.XTabLayout;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yyk.yykywd.R;
import com.yyk.yykywd.adapter.CommonTabPagerAdapter;
import com.yyk.yykywd.base.BaseFragment;
import com.yyk.yykywd.bean.IndexReportInfo;
import com.yyk.yykywd.config.HttpUrl;
import com.yyk.yykywd.http.Api;
import com.yyk.yykywd.http.ApiService;
import com.yyk.yykywd.bean.IndexLineInfo;
import com.yyk.yykywd.ui.work.CardWebActivity;
import com.yyk.yykywd.ui.YewutongzhiActivity;
import com.yyk.yykywd.ui.home.SimpleFragmentPagerAdapter;
import com.yyk.yykywd.util.Md5Util2;
import com.yyk.yykywd.util.OnClickFlagUtil;
import com.yyk.yykywd.widght.CustomViewPager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Android ScrollView嵌套(Tablyout)ViewPager＋Fragment时冲突问题解决办法 - Kenway090704的博客 - CSDN博客  https://blog.csdn.net/Kenway090704/article/details/79415702
 */
public class HomeFragment extends BaseFragment {
    public static final String TAG = "HomeFragment";
    @BindView(R.id.xblyout)
    XTabLayout xblyout;
    @BindView(R.id.vp)
    CustomViewPager vp;
    @BindView(R.id.viewfilipper)//不用了
            ViewFlipper viewfilipper;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.tv_text)
    TextView tvText;

    private CommonTabPagerAdapter tablyoutAdapter;
    private List<IndexLineInfo.DataBean> lineList;
    private String idType; //没用
    private int positionType;
    private SimpleFragmentPagerAdapter mAdapter;


    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    /************************************************************************/


    /************************************************************************/

    @Override
    public void initView() {
        initRefresh();
    }

    private void initRefresh() {
        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        postIndexReport(true);
                        postIndexLine();
                        //禁止点击内容
                        smartrefreshlayout.setDisableContentWhenRefresh(true);
                        smartrefreshlayout.finishRefresh();
                    }
                }, 1500);

            }
        });
    }

    @Override
    public void initData() {
        postIndexLine();
        postIndexReport(true);
    }

    /**
     * 初始化tablyout
     */
    private void initTablayout() {

        List<String> nameString = new ArrayList<>();
        nameString.add(0, "全部"); //在头部插入全部和0
        final List<Integer> idInteger = new ArrayList<>();
        idInteger.add(0, 0);
        for (int i = 0; i < lineList.size(); i++) {
            nameString.add(lineList.get(i).getName());
            idInteger.add(lineList.get(i).getId());
        }
        tablyoutAdapter = new CommonTabPagerAdapter(getChildFragmentManager()
                , nameString.size(), nameString, getActivity());
        tablyoutAdapter.setListener(new CommonTabPagerAdapter.TabPagerListener() {
            @Override
            public Fragment getFragment(int position) {
                BusinessLinesFragment fragment = BusinessLinesFragment.newInstance(position);
                Bundle bundle = new Bundle();
                positionType = position;
                idType = idInteger.get(position) + "";
                bundle.putString(BusinessLinesFragment.ARGS_PAGE, idInteger.get(position) + "");
                fragment.setArguments(bundle);
                return fragment;
            }
        });
        vp.setAdapter(tablyoutAdapter);
        xblyout.setupWithViewPager(vp);
        vp.setCurrentItem(0);
    }


    /**
     * 接口24.首页业务线状态（ggk）
     */
    private void postIndexLine() {
        Map<String, String> map = new TreeMap<>();
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postIndexLine(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Observer<IndexLineInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(IndexLineInfo info) {
                        Logger.e("首页业务线状态" + info.toString());
                        if (info.getCode() == 1) {
                            lineList = info.getData();
                            initTablayout();

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 接口10.业务通知列表（ggk）
     */
    private void postIndexReport(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
        map.put("uid", Hawk.get("uid") + "");
        map.put("page", 1 + "");
        map.put("num", 10000 + "");
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postIndexReport(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Observer<IndexReportInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(IndexReportInfo info) {
                        Logger.e("业务播报列表--标题" + info.toString());
                        if (info.getCode() == 1) {
                            final List<IndexReportInfo.DataBean> data = info.getData();
                            StringBuffer sb = new StringBuffer();
                            for (int i = 0; i < data.size(); i++) {
                                sb.append(data.get(i).getTitle() + "          ");
                            }
                            tvText.setText(sb.toString());

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 1.名片信息
     * 2.业务通知
     *
     * @param view
     */
    @OnClick({R.id.iv_cardmessage, R.id.tv_btyetzmore, R.id.tv_text})
    public void onViewClicked(View view) {
        if (OnClickFlagUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_cardmessage:
                //TODO 名片信息
                Intent intent = new Intent();
                intent.putExtra("url", HttpUrl.BASE_H5_URL + Api.NAMECARD);
//                intent.putExtra("title", "名片信息");
                startAct(intent, CardWebActivity.class, null);
                break;
            case R.id.tv_btyetzmore:
                startAct(YewutongzhiActivity.class);
                break;
            case R.id.tv_text:
                startAct(YewutongzhiActivity.class);
                break;
        }
    }


}
